package com.ywy.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * WebSocket配置
 *
 * @author ywy
 * @date 2021/12/29 15:17
 */
@Configuration
@EnableWebSocketMessageBroker // 开启使用STOMP协议来传输基于代理的消息
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    /**
     * 注册Stomp的端点
     *
     * @param registry
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // addEndpoint：添加STOMP协议的端点，提供WebSocket或SockJS客户端访问的地址
        // withSockJS：使用SockJS协议
        registry.addEndpoint("/websocket").withSockJS();
    }

    /**
     * 配置消息代理
     * 启动Broker，消息的发送的地址符合配置的前缀来的消息才发送到这个broker
     *
     * @param registry
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // user：点对点；topic：广播
        registry.enableSimpleBroker("/user/", "/topic/");
        // 推送消息前缀
        registry.setApplicationDestinationPrefixes("/app");
    }
}
